package us.gaaoc.framework.webapp.backingbeans.clerk;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

import sun.net.www.URLConnection;
import us.gaaoc.cms.Importer;
import us.gaaoc.cms.sustain.vo.Address;
import us.gaaoc.cms.sustain.vo.CaseDocument;
import us.gaaoc.cms.sustain.vo.CaseEvent;
import us.gaaoc.cms.sustain.vo.CaseFiling;
import us.gaaoc.cms.sustain.vo.CaseOfficial;
import us.gaaoc.cms.sustain.vo.CaseParty;
import us.gaaoc.cms.sustain.vo.Organization;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.CourtEventType;
import us.gaaoc.framework.model.CourtEvents;
import us.gaaoc.framework.model.CourtSeal;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.DocumentType;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LdapDirectoryOrganization;
import us.gaaoc.framework.model.LdapDirectoryPerson;
import us.gaaoc.framework.model.LocalCourtEventType;
import us.gaaoc.framework.model.LocalParticipantRelationship;
import us.gaaoc.framework.model.OrgParticipants;
import us.gaaoc.framework.model.OrganizationAddress;
import us.gaaoc.framework.model.Organizations;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.PersonAddress;
import us.gaaoc.framework.model.PersonParticipants;
import us.gaaoc.framework.model.constants.Constants;
import us.gaaoc.framework.signature.digital.DigitalSigner;
import us.gaaoc.framework.signature.digital.DigitalSignerController;
import us.gaaoc.framework.signature.digital.SignatureAndCertChain;
import us.gaaoc.framework.signature.visual.DocumentStamping;
import us.gaaoc.framework.signature.visual.PDFStamperController;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.util.DomToSustainConverter;
import us.gaaoc.framework.util.LocalCaseInformation;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.backingbeans.clerk.actions.GenericImportAction;
import us.gaaoc.framework.webapp.backingbeans.clerk.actions.GenericImportActionException;


/**
 * 
 * @author hea
 * @date Apr 28, 2006
 * @version: GAJE 1.5
 * 
 */
@SuppressWarnings("unchecked")
public class ImportConfirmationPage extends BaseBackingBean {

	/**
	 * Generated Serial Version ID
	 */
	private static final long serialVersionUID = 4788649085553901448L;

	/** properties */

	private String caseUuid;

	private Date courtDate;

	private boolean noContentsDocumentMessage = false;

	private boolean signatureFailureMessage = false;

	private boolean noCivilActionNumberStampMessage = false;

	private boolean noCourtReceivedStampMessage = false;

	private List<Documents> documentListWithoutContents = new ArrayList<Documents>();

	private List<Documents> documentListNotSignedByClerk = new ArrayList<Documents>();

	private List<Documents> documentListWithoutCourtReceivedStamp = new ArrayList<Documents>();

	private List<Documents> documentListWithoutCivilActionNumberStamp = new ArrayList<Documents>();
	// the following may not be used
	private Documents documentHasNoCivilActionNumberStamp;

	private PDFStamperController pdfStamperController = new PDFStamperController();

	private DigitalSignerController digitalSignerController = new DigitalSignerController();

	private static transient Logger LOG = Logger
	.getLogger(ImportConfirmationPage.class);
	
	private String courtUuid;
	
	// This is the holder for the text of the "import" button
	private String importButtonText;
	

	public ImportConfirmationPage() {
		courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
		caseUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("caseUuid");
		
		// This section sets the import button's text based on what court is currently logged in
		//TODO: move into properties file/database/etc.
		if(courtUuid.equals("courtUuid4") || courtUuid.equalsIgnoreCase("courtUuidClarke") || courtUuid.equals("courtUuidHouston") || courtUuid.equals("courtUuid5")|| courtUuid.equalsIgnoreCase("courtUuidBibb"))
		{
			importButtonText = "Queue For Import";
		}else{
			importButtonText = "Import";
		}
		

	}
	

	/**
	 * This method gets invoked when user clicks the import button to import the
	 * case into the Sustain.
	 * 
	 * Session map input:
	 * 	caseUuid - the case UUID to import
	 *  courtUuid - the courtUuid we are importing into.
	 *  person - the person object that is currently signing.
	 * 
	 * @return String
	 * @throws Exception
	 */
	@SuppressWarnings("null")
	public String importCaseRecord()  {
		LOG.debug("THE IMPORT PROCESS IS STARTING!!!! ");
		String returnString = "";
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		GenericImportAction importAction = new GenericImportAction();
		try {
			// We want to generalize the importAction away from the web beans.
			importAction.doImport(
					(String) sessionMap.get("caseUuid"), 
					(Person) sessionMap.get("person"),
					this.getModelFacade(),
					(String) sessionMap.get("courtUuid"));
			returnString = "gotoChildEnforcementCaseTypePage";
		} catch (GenericImportActionException e2) {
			// If the doImport generalized action is not supported, then fallback
			// on the other methods.
			
			if(courtUuid.equals("courtUuid4")){
				throw new UnsupportedOperationException("Fulton county import in another codebase");
			} else {
			
				// the import process starts when the clerk clicks on import which appears
				// only when the clerk signs all documents that need to be signed by the clerk
				String docketID = null;
				
		
				caseUuid = (String) sessionMap.get("caseUuid");
				courtUuid = (String) sessionMap.get("courtUuid");
				Court court = this.getModelFacade().findCourt(courtUuid);
				Person personSigned = (Person) sessionMap.get("person");
		
				this.setCourtDate((Date) sessionMap.get("courtDate"));
				
				String docketIDPlusJudgeCode = "";
				String judge = (String)sessionMap.get("judge");
				String judgeCode = "";
				String judgeSustainCode = "";
		
				CaseRecord cr = (CaseRecord) this.getModelFacade().findCaseRecordById(caseUuid, courtUuid);
		
				// Retrieve the LDAP person from LDAP server
				LdapDirectoryPerson ldPerson = this.getModelFacade().findLdapDirectoryByPerson(personSigned);
		
				String clerkRoleUuid = Constants.Roles.CLERKID; // The Clerk Role UUID
		
				// Initialize to blank in case no trackingID available
				String caseTrackingID = cr.getCaseTrackingId();
		
				// Set local codes based on court
				String divID = "";
		
				Organizations organization = null;
				LdapDirectoryOrganization ldOrganization = null;
				ldOrganization =this.getModelFacade().findLdapDirectoryByOrganization(court);
		
				divID = LocalCaseInformation.getDivID(courtUuid);
				organization = LocalCaseInformation.getCourtOrganization(courtUuid, this.getModelFacade());
		
				if(courtUuid.equalsIgnoreCase("courtUuid5"))
				{
					if (judge.equalsIgnoreCase("John H. Bailey")) {
						judgeCode = "J";
						judgeSustainCode = "JELJHB";
					} else if (judge.equalsIgnoreCase("Thomas H. Hodges")) {
						judgeCode = "H";
						judgeSustainCode = "JHATLH";
					} else if (judge.equalsIgnoreCase("Lindsay A. Tise")) {
						judgeCode = "T";
						judgeSustainCode = "JFRLAT";
					} else if (judge.equalsIgnoreCase("Jeffery S. Malcom")) {
						judgeCode = "M";
						judgeSustainCode = "JFRJSM";
					}
				}
		
				// Gather information needed for applying visual stamps and marks to pdf documents.
				List<Documents> documentList =  this.getModelFacade().getPDFDocuments(caseUuid);
		
				// Keep the original copy of the documents before stamping the court stamp and docket ID
				List<Documents> originalDocumentList = documentList;
		
				//Date submittedDate = this.getModelFacade().findAttorneySubmissionDate(cr.getUuid());
				Date submittedDate = DateUtil.getConditionalCurrentDate(courtUuid);
		
				DocumentStamping docStamping = new DocumentStamping();
				//NullImporter importer = new NullImporter(courtUuid);
				Importer importer = new Importer(courtUuid);
				
				/*
				 * If case exists, but hasn't been imported into Case Management System
				 */
				if ((caseUuid != null)&& ((caseTrackingID == null) || (caseTrackingID.equalsIgnoreCase("caseTrackingId")) || (caseTrackingID).equals(""))) 
				{
		
					//Documents textDoc = this.getModelFacade().getTextDocument(caseUuid);
		
					CaseFiling caseFiling = DomToSustainConverter.createCaseFiling(this.getModelFacade(),cr, court);
					
					//caseFiling.setJudgeCode(judgeSustainCode);
					
					// 1. insert CMS
					try {
						//docketID = importer.doImport(caseFiling,courtUuid,"clerkUuid3");
						docketID = importer.doImport(caseFiling, courtUuid, personSigned.getUuid());
						//docketID = "08CV01010";
					} catch (Exception e) {	
						new Exception("Failure in Importer " + cr.getUuid()).printStackTrace();
						e.printStackTrace();
						this.changeStatusAsCourtStampFailed(originalDocumentList);
						return "stay";
					}
					this.getModelFacade().updateCaseRecordCourtTrackingID(caseUuid, docketID, courtUuid);
		
					// DEBUG - Static Docket ID for testing
					// docketID="08CS00001";
		
					// 2. add court stamp and docket id on pdf
					// TODO Need to finish updating of adding digital signature when
					// stamping
		
					List<Documents> stampedDocsList = new ArrayList<Documents>();
					List<Documents> docketedDocsList = new ArrayList<Documents>();
		
					
					if(courtUuid.equalsIgnoreCase("courtUuid3"))
					{
						Iterator iter = documentList.iterator();
						while(iter.hasNext())
						{
							Documents d = (Documents) iter.next();
							// not imported summons and rules nisi and not imported show cause
							if((d.getDocumentInstance().getCode() == 197 || d.getDocumentInstance().getCode() == 196) && d.getStatus().getCode() != 2)
							{					
								d.setStatus(this.getModelFacade().findDocumentStatus(Constants.DocumentStatus.SIGNED_BY_CLERK));
								//break;
							}					
						}
					}
					
					
					// the following documentsReadyForCourtReceivedStamp method
					// returns a string indicating whether the list of docs is ready
					// for court received stamp or not. In the process of doing so
					// it checks if the proper docs are signed by the clerk
					// THE FOLLOWING SIX LINES ARE FOR DEBUGGING PURPOSES ONLY. When
					// executing application comment the below three lines out
					/*
					 * documentList.get(1).setContent(null);
					 * documentList.get(2).setContent(null);
					 * documentList.get(3).setContent(null);
					 */
					byte[] sigInByte = null;
					int documentManagerStatusCode = 0;
					documentManagerStatusCode = docStamping.documentsReadyForCourtReceivedStamp(documentList);
		
					// System.out.println(stateOfTheDocumentListForCourtReceivedStamp);
					// {3 = "documentsReadyForCourtReceivedStamp"}
					if (documentManagerStatusCode == 3) {
						System.out.println("documents are ready for court received stamp");
						// stamp the documentList with the court's stamp
						stampedDocsList = pdfStamperController.applyCourtReceivedStamp(documentList, submittedDate, personSigned, courtUuid);
		
						//if visual signature and court stamp is applied then put the docket id
						if (pdfStamperController.isStampedDoc() == true) {
							System.out.println("ready to check if the documents are ready for civil action number stamp");
							documentManagerStatusCode = docStamping.documentsReadyForCivilActionNumberStamp(stampedDocsList);
							
		
							
							
							// stamp the stampedDocsList with the civil action number stamp
							// {5 = "documentsReadyForCivilActionNumberStamp"}
							if (documentManagerStatusCode == 5) {
								// Append judge's code to docket ID
								if (courtUuid.equalsIgnoreCase("courtUuid5")) {
									docketIDPlusJudgeCode = docketID + judgeCode;
									docketedDocsList = pdfStamperController.applyDocketIdStamp(stampedDocsList, docketIDPlusJudgeCode,personSigned);
								} else
								{
									docketedDocsList = pdfStamperController.applyDocketIdStamp(stampedDocsList, docketID,personSigned);
								}
		
								Iterator iter = docketedDocsList.iterator();
								while(iter.hasNext())
								{
									Documents d = (Documents)iter.next();
									if(d.getDocumentInstance().getCode() == 197 || d.getDocumentInstance().getCode() == 196){
										iter.remove();
									}
								}
								
								// If visual Signature is successfully put on the document then digitally sign
								if (pdfStamperController.isDocketIDStamped() == true) {
									
		
									for (Documents document : docketedDocsList) {
									// b7006e6c-695c-11dd-945f-00301b45ff56
										//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
										if (document.getDocumentInstance().getCode() != 181) {
											try {
												sigInByte = digitalSignerController.signPDFDocument(document,personSigned,clerkRoleUuid, ldPerson);
											} catch (Exception e) {
												new Exception("Failed to sign " + cr.getUuid());
												e.printStackTrace();
												this.changeStatusAsCourtStampFailed(originalDocumentList);
												return "stay";
											}
		
											// update the signed field in the documents object
											System.out.println("Document is "+ document.getTitle()	+ "and Status = "+ document.getStatus().getCode());
											if (digitalSignerController.isSignedDoc() == true) {
												DocumentStatus documentStatus = new DocumentStatus();
												int statusCode = Constants.DocumentStatus.STAMPED_WITH_COURT_RECEIVED_STAMP; // stamped with court received stamp										
												documentStatus = this.getModelFacade().findDocumentStatus(statusCode);
												document.setStatus(documentStatus);
												try {
													digitalSignerController.updateDatabaseAfterSigned(document,documentStatus,personSigned, sigInByte);
												} catch (CertificateException e) {
													new Exception("Failed to update db after signed " + cr.getUuid());
													e.printStackTrace();
													this.changeStatusAsCourtStampFailed(originalDocumentList);											
													return "stay";
												} catch (IOException e) {
													new Exception("Failed to update db after signed " + cr.getUuid());
													e.printStackTrace();
													this.changeStatusAsCourtStampFailed(originalDocumentList);
													return "stay";
												}
											} else {
												new Exception("Court stamp failed " + cr.getUuid()).printStackTrace();
												this.changeStatusAsCourtStampFailed(originalDocumentList);
												return "stay";
											}
										} else {
											DocumentStatus documentStatus = new DocumentStatus();
											int statusCode = Constants.DocumentStatus.STAMPED_WITH_COURT_RECEIVED_STAMP; // stamped with court
											// received stamp
											documentStatus = this.getModelFacade().findDocumentStatus(statusCode);
											document.setStatus(documentStatus);
											this.getModelFacade().updateDocumentStatus(document.getUuid(), documentStatus);
										}
									}
								}
								else {
									new Exception("Docket ID is not stamped " + cr.getUuid()).printStackTrace();
									this.changeStatusAsCourtStampFailed(originalDocumentList);
									return "stay";
								}
							} else {
								new Exception("Docket ID FAILED " + cr.getUuid()).printStackTrace();
								this.changeStatusAsCourtStampFailed(originalDocumentList);
								return "stay";
							}
						} else {
							new Exception("Documents are not ready for court received stamp " + cr.getUuid()).printStackTrace();
							this.changeStatusAsCourtStampFailed(originalDocumentList);
							return "stay";
						}
						/*
						if (docStamping	.checkDocumentListForCourtReceivedStamp(stampedDocsList)) {
							System.out.println("ready to check if the documents are ready for civil action number stamp");
							int stateOfTheDocumentListForCivilActionNumberStamp = docStamping.documentsReadyForCivilActionNumberStamp(stampedDocsList);
		
							// stamp the stampedDocsList with the civil action number stamp
							// {5 = "documentsReadyForCivilActionNumberStamp"}
							if (stateOfTheDocumentListForCivilActionNumberStamp == 5) {
								docketedDocsList = pdfStamperController.applyDocketIdStamp(stampedDocsList, docketID,personSigned);\
						 */
						if (docStamping.checkDocumentListForCivilActionNumberStamp(docketedDocsList)) {
		
							// 3. import the modified pdf to sustain
							caseFiling.setDocuments(docStamping	.createCaseDocumentListFromDocumentList(docketedDocsList));
							try {
								importer.importDocuments(caseFiling);//, courtUuid, clerkRoleUuid);
							} catch (Exception e) {
								new Exception("Failed to import documents "  + cr.getUuid()).printStackTrace();
								e.printStackTrace();
								
								this.changeStatusAsCourtStampFailed(originalDocumentList);
								return "stay";
							}
							//updateDocumentStatusToImported(docketedDocsList);
							//@TODO after importing put the court seal on each document.....sealed by Court 
							try {
								this.courtSealDocuments(docketedDocsList,organization,ldOrganization);
							} catch (Exception e) {
								e.printStackTrace();
								this.changeStatusAsCourtStampFailed(originalDocumentList);
								return "stay";
							}
							//for imported documents statusCode=2
							DocumentStatus ds = this.getModelFacade().findDocumentStatus(Constants.DocumentStatus.IMPORTED);
							//change the status of documents after importing into the sustain
							updateDocumentStatusToImported(docketedDocsList);
							// We do not keep DATA FILE's in our database anymore
							//this.getModelFacade().updateDocumentStatus(textDoc.getUuid(),ds);
							// 4. update caseRecord -- caseRecordStatus =
							// imported
							// (2)
							this.getModelFacade().updateImportedCaseRecord(
									caseUuid, docketID, 2, courtUuid);
							// 5. update caseReocrd history --
							// caseRecordEventType =
							// imported
							// (2)
							this.getModelFacade().addCaseRecordHistory(
									caseUuid, 2, personSigned, courtUuid,"no comments");
							// 6. insert filing search
							// Modified by Frank on 2.25.2008
							//this.insertFilingSearch(documentList, docketID, caseUuid);
							this.insertFilingSearch(docketedDocsList, docketID, caseUuid);
							// 7. commit the transaction
							//  b7006e6c-695c-11dd-945f-00301b45ff56
							//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
							sessionMap.put("from", "importConfirmationPage");
							returnString = "gotoChildEnforcementCaseTypePage";
						} else {
							this.changeStatusAsCourtStampFailed(originalDocumentList);
							new Exception("CV Number not on documents " + cr.getUuid()).printStackTrace();
							returnString = "stay";
						}
						// {1= "noContentsDocument"}
					} else if (documentManagerStatusCode == 1) {
						this.documentListWithoutContents = docStamping.documentListWithoutContents(documentList);
						this.getModelFacade().addCaseRecordHistory(caseUuid,18, personSigned, courtUuid,"no comments");
						this.setNoContentsDocumentMessage(true);
						this.changeStatusAsCourtStampFailed(originalDocumentList);
						new Exception("A document has no contents! "  + cr.getUuid()).printStackTrace();
						returnString = "stay";
						// {4 = "documentListWithoutCourtReceivedStamp"}
					} else if (documentManagerStatusCode == 4) {
						this.documentListWithoutCourtReceivedStamp = docStamping.documentListWithoutCourtReceivedStamp(documentList);
						this.getModelFacade().addCaseRecordHistory(caseUuid,20, personSigned, courtUuid,"no comments");
						this.setNoCourtReceivedStampMessage(true);
						this.changeStatusAsCourtStampFailed(originalDocumentList);
						new Exception("A document has no court recieved stamp " + cr.getUuid()).printStackTrace();
						returnString = "stay";
					} else {
						new Exception("Court received stamp failed in some documents " + cr.getUuid()).printStackTrace();
						this.documentListWithoutCourtReceivedStamp = docStamping.documentListWithoutCourtReceivedStamp(documentList);
						this.getModelFacade().addCaseRecordHistory(caseUuid, 20,personSigned, courtUuid,"no comments");
						this.setNoCourtReceivedStampMessage(true);
						
						returnString = "stay";
					}
				}
		
				/*
				 * If the case is existing i.e. pulled from the CMS to modify then
				 * import only new documents into the CMS
				 */
				else if ((caseUuid != null) && ((caseTrackingID != null) || !(caseTrackingID).equals(""))) {
					byte[] sigInByte = null;
					docketID = caseTrackingID;
					List<Documents> newDocumentList = new ArrayList<Documents>();
					ArrayList<CaseDocument> addedPdfDocList = new ArrayList<CaseDocument>();
					/*
					 * Determine which documents need to be imported by checking their
					 * status codes.
					 */
					CaseFiling caseFiling = DomToSustainConverter.createCaseFiling(this.getModelFacade(),cr, court);
					
					if (documentList != null && !documentList.isEmpty()) {
						for (Documents doc : documentList) {
							int docStatusCode = doc.getStatus().getCode();
							// Document status is uploaded (6) or signed by the clerk or
							// the attorney
							if ((docStatusCode == 6) 				//upload
									|| (docStatusCode == 8)			//signedByClerk
									|| (docStatusCode == 11)		//signedByAttorney
									|| (docStatusCode == 9)			//stampedWithCourtReceivedStamp
									|| (docStatusCode == 10) 		//stampedWithCourtCVNumber
									|| (docStatusCode == 12)) {		//courtStampFailed
		
								System.out.println("This document "	+ doc.getTitle()
										+ " must be appended to the list of the " +
										"new documents that must be inserted to " +
								"the local management case");
								newDocumentList.add(doc);
							}
						}
					}
		
					// 2. Stamp and Apply Docket ID to new documents
					int stateOfTheDocumentListForCourtReceivedStamp = docStamping
					.documentsReadyForCourtReceivedStamp(newDocumentList);
					// {3 = "documentsReadyForCourtReceivedStamp"
					if (stateOfTheDocumentListForCourtReceivedStamp == 3) {
						// stamp the additional to an existing case files with the
						// courts's stamp
						List<Documents> additionalStampedDocsList = pdfStamperController
						.applyCourtReceivedStamp(newDocumentList,
								submittedDate, personSigned, courtUuid);
						int docTypeCode = 0;
						boolean docTypeCheck = false; //To check if the document is Summons and Rule Nisi
						for (Documents doc : additionalStampedDocsList) {
							docTypeCode = doc.getDocumentInstance().getDocumentType()
							.getCode();
							if (docTypeCode == 34 || docTypeCode == 27) {
								docTypeCheck = true;
							}				
						}
						//if (docStamping.checkDocumentListForCourtReceivedStamp(additionalStampedDocsList)) {
						//if visual signature and court stamp is applied then put the docket id
						
						
						for(Documents doc : additionalStampedDocsList)
						{
							if(doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode() != Constants.DocumentCategory.ORDER)
							{
								doc.setContent(null,pdfStamperController.applyDocketIdStampOnOneDoc(doc,cr.getCaseTrackingId() + judgeCode, personSigned));
							}
						}
						
						if ((pdfStamperController.isStampedDoc() == true) || (docTypeCheck == true) ) {
							/*
							 * No need to apply dockt ID to the scanned documents
							 * 
							System.out.println("ready to check if the documents are ready for civil action number stamp");
							int stateOfTheDocumentListForCivilActionNumberStamp = docStamping
									.documentsReadyForCivilActionNumberStamp(additionalStampedDocsList);
							// stamp the stampedDocsList with the civil action number
							// stamp
							// {5 = "documentsReadyForCivilActionNumberStamp"}
							if (stateOfTheDocumentListForCivilActionNumberStamp == 5) {
								List<Documents> additionalDocketedDocsList = pdfStamperController
										.applyDocketIdStamp(additionalStampedDocsList,
												docketID, personSigned);
		
								if (docStamping
										.checkDocumentListForCivilActionNumberStamp(additionalDocketedDocsList)) {
							
							 */
							try {
								this.signDocuments(additionalStampedDocsList, personSigned, clerkRoleUuid, ldPerson);
							} catch (Exception e1) {
								e1.printStackTrace();
								this.changeStatusAsCourtStampFailed(originalDocumentList);
								return "stay";
							}
		
							// and the digital is missing
		
							// Find and Count the number of documents already in
							// the system
							//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
							List<Documents> totalDocumentList = this
							.getModelFacade().findDocumentsByCaseUuid(
									caseUuid);
							int documentsImportedCount = 0;
							for (Documents doc : totalDocumentList) {
								docTypeCode = doc.getDocumentInstance()
								.getDocumentType().getCode();
								int docStatusCode = doc.getStatus().getCode();
								if (docStatusCode == Constants.DocumentStatus.IMPORTED) {
									documentsImportedCount++;
								}
		
							}
		
							// 3. Import New Documents to Case Management System
							
							addedPdfDocList = docStamping
							.createCaseDocumentListFromDocumentList(additionalStampedDocsList);
							caseFiling.setDocuments(addedPdfDocList);
							try {
								importer.importNewDocuments(addedPdfDocList, caseFiling, divID,
										docketID, submittedDate,
										documentsImportedCount); //courtUuid, clerkRoleUuid);
								//@TODO add court seal on the new imported documents
								this.courtSealDocuments(additionalStampedDocsList, organization,ldOrganization);
								updateDocumentStatusToImported(additionalStampedDocsList);
			
								/*
								 * right now we are not using this condition but in future we might
								 * 
										boolean orderDoc = false;
										for (Documents d : newDocumentList) {
											orderDoc = digitalSignerController.isDocumentOrderForClerk(d);
											if (orderDoc) {
											} else {
											}
										}
								 */
								
								/*
								 * Check for the new uploaded documents has the disposition document in the Case
								 * if disposition document found then dismiss the case and change the status as disposed
								 * otherwise just mark as imported and change the caseRecord history as per the consition. 
								 */
								boolean dispositionDoc = false;
								for(Documents d : additionalStampedDocsList) {
									dispositionDoc = this.isDispositionDoc(d);
									if (dispositionDoc) {
										// update the case Record to the disposed status
										this.getModelFacade().updateImportedCaseRecord(caseUuid, docketID, Constants.CaseRecordStatus.DISPOSED, courtUuid);
										// 5. update caseReocrd history --disposed (6)
										this.getModelFacade().addCaseRecordHistory(caseUuid, Constants.CaseRecordEventType.FILING_DISPOSED, personSigned, courtUuid,"no comments");
									} else {
										//update the case record as imported status
										this.getModelFacade().updateImportedCaseRecord(caseUuid, docketID, Constants.CaseRecordStatus.IMPORTED, courtUuid);
										// 5. update caseReocrd history --imported(2)	
										this.getModelFacade().addCaseRecordHistory(caseUuid, Constants.CaseRecordEventType.FILING_IMPORTED_TO_CMS, personSigned, courtUuid,"no comments");
									}
								}
			
								// 6. insert filing search
								this.insertFilingSearch(additionalStampedDocsList, docketID,
										caseUuid);
							
								// 	b7006e6c-695c-11dd-945f-00301b45ff56
								// 7. commit the transaction
								//HibernatePhaseListener.getSessionFactory()
								//.getCurrentSession().getTransaction()
								//.commit();
								
								returnString = "gotoChildEnforcementCaseTypePage";
							} catch (Exception e) {
								new Exception("ImportNewDocuments failed: " + caseTrackingID ).printStackTrace();
								e.printStackTrace();
								this.setNoCourtReceivedStampMessage(true);
								this.changeStatusAsCourtStampFailed(originalDocumentList);
								returnString = "stay";
								
							}
						
						} else {
							System.out.println("There are documents with no court received stamp");
							new Exception("There are documents with no court received stamp " + caseTrackingID ).printStackTrace();
							this.documentListWithoutCourtReceivedStamp = docStamping.documentListWithoutCourtReceivedStamp(documentList);
							this.getModelFacade().addCaseRecordHistory(	caseUuid, 20, personSigned, courtUuid,"no comments");
							this.setNoCivilActionNumberStampMessage(true);
							this.changeStatusAsCourtStampFailed(originalDocumentList);
							returnString = "stay";
						}
					}
					else {
						System.out
						.println("Court received stamp failed in some documents");
						new Exception("Court received stamp failed in some documents " + caseTrackingID ).printStackTrace();
						this.documentListWithoutCourtReceivedStamp = docStamping
						.documentListWithoutCourtReceivedStamp(documentList);
						this.getModelFacade().addCaseRecordHistory(caseUuid, 20,
								personSigned, courtUuid,"no comments");
						this.setNoCourtReceivedStampMessage(true);
						this.changeStatusAsCourtStampFailed(originalDocumentList);
						returnString = "stay";
					}
				}
			}
		}
		return returnString;
	}

	/**
	 * @param d
	 * @return
	 */
	private boolean isDispositionDoc(Documents doc) {
		DocumentType documentType = doc.getDocumentInstance().getDocumentType();
		int docTypeCode = documentType.getCode();

		boolean documentDisposition = false;

		if(docTypeCode == Constants.DocumentType.FORM_DISPOSITION ){
			LOG.info("The document code is " + docTypeCode);
			documentDisposition = true;
		}
		else {
			documentDisposition = false;

		}
		return documentDisposition;
	}

	/**
	 * This method seals the document as court signs the documents 
	 * which has court stamp, docket id, digital signature and 
	 * imported into the sustain.
	 * @param docketedDocsList
	 * @param court=>organization
	 * @param ldPerson
	 */
	private void courtSealDocuments(List<Documents> docketedDocsList,
			Organizations organization, LdapDirectoryOrganization ldOrganization) {
		// TODO Auto-generated method stub
		DigitalSigner digitalSigner = new DigitalSigner();
		String cnName = ldOrganization.getCname();
		String password = ldOrganization.getCertPassword();

		byte[] csv = null;  //Court Seal Value
		for (Documents doc : docketedDocsList) {
			
			if(this.getModelFacade().findCourtSealByDocumentID(doc.getUuid()) == null)
			{			
				ByteArrayInputStream bais = new ByteArrayInputStream(doc.getContent());
				csv = digitalSigner.sign(bais, cnName, password);
				CourtSeal courtSeal = new CourtSeal();
				courtSeal.setSignedByOrganization(organization);
				courtSeal.setCourtSealValue(csv);
				courtSeal.setCreationDate(new Date());
				courtSeal.setDocument(doc);
				courtSeal.setCertificateChain(SignatureAndCertChain.certificationChain);
				SimpleDateFormat simpformatter = new SimpleDateFormat("MM/dd/yy");
				String expireString = "01/01/16";
				ParsePosition pp = new ParsePosition(0);
				Date expirationDate = simpformatter.parse(expireString, pp);
				courtSeal.setExpirationDate(expirationDate);
				doc.setCourtSeal(courtSeal);
				//this.getModelFacade().makePersistenet(doc);
				this.getModelFacade().insertCourtSeal(courtSeal);
			}
		}		
	}

	private void changeStatusAsCourtStampFailed(List<Documents> originalDocList) {
		for(Documents doc  : originalDocList) {
			//do not change the status of the imported documents
			if(doc.getStatus().getCode() != Constants.DocumentStatus.IMPORTED){
				byte[] originalDocContent = doc.getContent();
				doc.setContent(null,originalDocContent);
				DocumentStatus ds = this.getModelFacade().findDocumentStatus(Constants.DocumentStatus.FAILED_COURT_RECEIVED_STAMP);
				doc.setStatus(ds);
			}
		}

	}

	public String gotoRejectFilingFromImportPrecess() {
		System.out.println("Inside the goToRejectFiling method ");
		Map sessionMap = this.getFacesContext().getExternalContext()
		.getSessionMap();
		sessionMap.put("importFilingConfirmation", this);
		System.out.println("sent to rejectFiling.xhtml ");
		//return "gotoRejectFilingFromImportPrecess";
		return "reject";
	}

	private void insertFilingSearch(List<Documents> attachmentList,
			String docketID, String caseRecordUuid) {
		Iterator iter = attachmentList.iterator();
		Documents doc = null;
		try {
			while (iter.hasNext()) {
				doc = (Documents) iter.next();

				InputStream bais = new ByteArrayInputStream(doc.getContent());

				// If not xml or a text file, the strip out the text content
				// for searching.
				if (!doc.getPhysicalType().equalsIgnoreCase("xml")
						&& !doc.getPhysicalType().equalsIgnoreCase("text")) {
					// Load the PDF from the input stream
					PDDocument thePDF = PDDocument.load(bais);
					PDFTextStripper stripper = new PDFTextStripper();

					// Get the text from the PDF
					String documentText = stripper.getText(thePDF);

					// Save the data
					this.getModelFacade().insertFilingSearch(documentText,
							doc.getTitle(), docketID, caseRecordUuid);

					// IMPORTANT! Close the PDF stream
					thePDF.close();
				}

			}
		} catch (IOException e) {
			e.printStackTrace();

		}
	}

	public void signDocuments(List<Documents> docsToSignPassedIn, Person personSigned, String clerkRoleUuid, LdapDirectoryPerson ldPerson) throws Exception {
		for(Documents doc : docsToSignPassedIn) {
			digitalSignerController.signPDFDocument(doc, personSigned, clerkRoleUuid, ldPerson);
		}

	}

	public void updateDocumentStatusToImported(List<Documents> docsToUpdatePassedIn) {
		List<Documents> docsToUpdate = docsToUpdatePassedIn;
		String docUuid;
		DocumentStatus documentStatus = new DocumentStatus();
		documentStatus = this.getModelFacade().findDocumentStatus(Constants.DocumentStatus.IMPORTED);
		for (Documents doc : docsToUpdate) {
			docUuid = doc.getUuid();
			this.getModelFacade().updateDocumentStatus(docUuid, documentStatus);
		}
	}

	public java.lang.String rejectCaseRecord() throws Exception {
		return "gotoChildEnforcementCaseTypePage";
	}

	/**
	 * This method builds a CaseFiling based on the given CaseRecord for import
	 * to CMS (Sustain).
	 * 
	 * @param cr
	 * @return
	 */



	public boolean isNoContentsDocumentMessage() {
		return noContentsDocumentMessage;
	}

	public void setNoContentsDocumentMessage(boolean noContentsDocumentMessage) {
		this.noContentsDocumentMessage = noContentsDocumentMessage;
	}

	public boolean isSignatureFailureMessage() {
		return signatureFailureMessage;
	}

	public void setSignatureFailureMessage(boolean signatureFailureMessage) {
		this.signatureFailureMessage = signatureFailureMessage;
	}

	public Documents getDocumentHasNoCivilActionNumberStamp() {
		return documentHasNoCivilActionNumberStamp;
	}

	public void setDocumentHasNoCivilActionNumberStamp(
			Documents documentHasNoCivilActionNumberStamp) {
		this.documentHasNoCivilActionNumberStamp = documentHasNoCivilActionNumberStamp;
	}

	public boolean isNoCivilActionNumberStampMessage() {
		return noCivilActionNumberStampMessage;
	}

	public void setNoCivilActionNumberStampMessage(
			boolean noCivilActionNumberStampMessage) {
		this.noCivilActionNumberStampMessage = noCivilActionNumberStampMessage;
	}

	public List<Documents> getDocumentListWithoutContents() {
		return documentListWithoutContents;
	}

	public void setDocumentListWithoutContents(
			List<Documents> documentListWithoutContents) {
		this.documentListWithoutContents = documentListWithoutContents;
	}

	public List<Documents> getDocumentListNotSignedByClerk() {
		return documentListNotSignedByClerk;
	}

	public void setDocumentListNotSignedByClerk(
			List<Documents> documentListNotSignedByClerk) {
		this.documentListNotSignedByClerk = documentListNotSignedByClerk;
	}

	public List<Documents> getDocumentListWithoutCourtReceivedStamp() {
		return documentListWithoutCourtReceivedStamp;
	}

	public void setDocumentListWithoutCourtReceivedStamp(
			List<Documents> documentListWithoutCourtReceivedStamp) {
		this.documentListWithoutCourtReceivedStamp = documentListWithoutCourtReceivedStamp;
	}

	public List<Documents> getDocumentListWithoutCivilActionNumberStamp() {
		return documentListWithoutCivilActionNumberStamp;
	}

	public void setDocumentListWithoutCivilActionNumberStamp(
			List<Documents> documentListWithoutCivilActionNumberStamp) {
		this.documentListWithoutCivilActionNumberStamp = documentListWithoutCivilActionNumberStamp;
	}

	public boolean isNoCourtReceivedStampMessage() {
		return noCourtReceivedStampMessage;
	}

	public void setNoCourtReceivedStampMessage(
			boolean noCourtReceivedStampMessage) {
		this.noCourtReceivedStampMessage = noCourtReceivedStampMessage;
	}
	
	/**
	 * @return Returns the courtDate.
	 */
	public Date getCourtDate() {
		return courtDate;
	}

	/**
	 * @param courtDate
	 *            The courtDate to set.
	 */
	public void setCourtDate(Date courtDate) {
		this.courtDate = courtDate;
	}

	/**
	 * @return Returns the caseUuid.
	 */
	public String getCaseUuid() {
		return caseUuid;
	}

	/**
	 * @param caseUuid
	 *            The caseUuid to set.
	 */
	public void setCaseUuid(String caseUuid) {
		this.caseUuid = caseUuid;
	}

	public String getImportButtonText() {
		return importButtonText;
	}
}
